package middleware

import (
	"net/http"
	"strings"

	"awesomeProject/pkg/auth"
	"awesomeProject/pkg/errors"
	"github.com/gin-gonic/gin"
)

// AuthMiddleware JWT认证中间件
func AuthMiddleware(jwtManager *auth.JWTManager) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头获取Authorization
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "Authorization header is required",
				"code":  errors.Unauthorized,
			})
			c.Abort()
			return
		}

		// 检查Bearer前缀
		if !strings.HasPrefix(authHeader, "Bearer ") {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "Invalid authorization header format",
				"code":  errors.Unauthorized,
			})
			c.Abort()
			return
		}

		// 提取token
		tokenString := strings.TrimPrefix(authHeader, "Bearer ")
		if tokenString == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "Token is required",
				"code":  errors.Unauthorized,
			})
			c.Abort()
			return
		}

		// 验证token
		claims, err := jwtManager.VerifyToken(tokenString)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "Invalid or expired token",
				"code":  errors.Unauthorized,
			})
			c.Abort()
			return
		}

		// 将用户信息存储到上下文中
		c.Set("user_id", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("user_role", claims.Role)
		c.Set("token", tokenString)

		// 继续处理请求
		c.Next()
	}
}

// AdminMiddleware 管理员权限中间件
func AdminMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取用户角色
		userRole, exists := c.Get("user_role")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "User role not found in context",
				"code":  errors.Unauthorized,
			})
			c.Abort()
			return
		}

		// 检查是否为管理员
		if userRole.(string) != "admin" {
			c.JSON(http.StatusForbidden, gin.H{
				"error": "Admin privileges required",
				"code":  errors.Forbidden,
			})
			c.Abort()
			return
		}

		// 继续处理请求
		c.Next()
	}
}

// OptionalAuthMiddleware 可选认证中间件（不强制要求认证）
func OptionalAuthMiddleware(jwtManager *auth.JWTManager) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头获取Authorization
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			// 没有认证信息，继续处理但不设置用户信息
			c.Next()
			return
		}

		// 检查Bearer前缀
		if !strings.HasPrefix(authHeader, "Bearer ") {
			c.Next()
			return
		}

		// 提取token
		tokenString := strings.TrimPrefix(authHeader, "Bearer ")
		if tokenString == "" {
			c.Next()
			return
		}

		// 验证token
		claims, err := jwtManager.VerifyToken(tokenString)
		if err != nil {
			// token无效，继续处理但不设置用户信息
			c.Next()
			return
		}

		// 将用户信息存储到上下文中
		c.Set("user_id", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("user_role", claims.Role)
		c.Set("token", tokenString)

		// 继续处理请求
		c.Next()
	}
}

// RoleMiddleware 角色权限中间件
func RoleMiddleware(allowedRoles ...string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取用户角色
		userRole, exists := c.Get("user_role")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "User role not found in context",
				"code":  errors.Unauthorized,
			})
			c.Abort()
			return
		}

		// 检查用户角色是否在允许的角色列表中
		userRoleStr := userRole.(string)
		for _, role := range allowedRoles {
			if userRoleStr == role {
				c.Next()
				return
			}
		}

		// 用户角色不在允许列表中
		c.JSON(http.StatusForbidden, gin.H{
			"error": "Insufficient privileges",
			"code":  errors.Forbidden,
		})
		c.Abort()
	}
}

// OwnerOrAdminMiddleware 资源所有者或管理员权限中间件
func OwnerOrAdminMiddleware(resourceUserIDKey string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取当前用户ID和角色
		currentUserID, exists := c.Get("user_id")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "User ID not found in context",
				"code":  errors.Unauthorized,
			})
			c.Abort()
			return
		}

		userRole, exists := c.Get("user_role")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "User role not found in context",
				"code":  errors.Unauthorized,
			})
			c.Abort()
			return
		}

		// 如果是管理员，直接通过
		if userRole.(string) == "admin" {
			c.Next()
			return
		}

		// 获取资源所有者ID
		resourceUserID, exists := c.Get(resourceUserIDKey)
		if !exists {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": "Resource user ID not found",
				"code":  errors.InvalidParams,
			})
			c.Abort()
			return
		}

		// 检查是否为资源所有者
		if currentUserID.(uint) == resourceUserID.(uint) {
			c.Next()
			return
		}

		// 既不是管理员也不是资源所有者
		c.JSON(http.StatusForbidden, gin.H{
			"error": "Access denied: not resource owner or admin",
			"code":  errors.Forbidden,
		})
		c.Abort()
	}
}